package com.scx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scx.context.BaseContext;
import com.scx.entity.Follow;
import com.scx.entity.User;
import com.scx.mapper.FollowMapper;
import com.scx.result.Result;
import com.scx.service.FollowService;
import com.scx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;

    @Override
    public Result isFollow(Long followUserId) {
        Integer count = query().eq("user_id", BaseContext.getCurrentId())
                .eq("follow_user_id", followUserId).count();
        return Result.success(count > 0);
    }

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        Long userId = BaseContext.getCurrentId();
        String key = "follows:" + userId;
        if (isFollow) {
            //关注
            Follow follow = new Follow();
            follow.setFollowUserId(followUserId);
            follow.setUserId(userId);
            boolean save = save(follow);
            if (save) {
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }
        } else {
            //取关
            QueryWrapper<Follow> qw = new QueryWrapper<>();
            qw.eq("user_id", userId);
            qw.eq("follow_user_id", followUserId);
            boolean remove = remove(qw);
            if (remove) {
                stringRedisTemplate.opsForSet().remove(key);
            }
        }
        return Result.success();
    }

    @Override
    public Result followCommons(Long id) {
        Long userId = BaseContext.getCurrentId();
        String key = "follows:" + userId;
        String key2 = "follows:" + id;
        //求交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if (intersect == null || intersect.isEmpty()) {
            return Result.success();
        }
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<User> userDTOList = userService.listByIds(ids).stream().
                map(user -> BeanUtil.toBean(user, User.class)).collect(Collectors.toList());
        return Result.success(userDTOList);
    }
}
